#!/bin/bash
if [ ! -n "$1" ] ;then
    echo " not input a sdk url (download or local path)!"
    exit;
else
    echo " sdk url is $1"
fi

if [ ! -n "$2" ] ;then
    echo " not input a sdk verson 3.0.0 、2.9.0 、carbon"
    exit;
else
    echo " sdk verson is $1"
fi

if [ -z "$PROJECT_PATH" ]; then
    PROJECT_PATH="./"
fi

SDK_PATH="Agora_Native_SDK_for_Mac_FULL"

DST_PATH="sdk_files/AgoraRtcSdk/Libs/"

SRC_JSON="frameworks/Dumps/apis.json"

RES_PATH="sdk_files/AgoraRtcSdk/dumps/"

DST_JSON="${RES_PATH}/apis.json"

SDK_ZIP_PATH=$1

DEL_ZIP=false

HTTP_URL=${SDK_ZIP_PATH:0:4}

if [ "$HTTP_URL" == "http" ];then
    
    URL=$1
    msg=$(curl -I -s --connect-timeout 5 "$URL" -w %{http_code} | tail -n 1)
    if [ "${msg}" == "200" ]; then
        echo " start download 0 {$URL} "
    else

        URL=${URL/artifactory.agoralab.co/accs-bot:accsbot123@artifactory-api.bj2.agoralab.co}
        URL=${URL/artifactory-api.bj2.agoralab.co/accs-bot:accsbot123@artifactory-api.bj2.agoralab.co}
        msg=$(curl -I -s --connect-timeout 5 "$URL" -w %{http_code} | tail -n 1)
        if [ "${msg}" == "200" ]; then
            echo " start download 1 {$URL} "
        else
            echo " download err ${msg} $URL"
            exit;
        fi
    fi

    SDK_ZIP_PATH=$PROJECT_PATH/${SDK_PATH}.zip
    
    wget $URL -O $SDK_ZIP_PATH

    DEL_ZIP=true

else

    SDK_ZIP_PATH=$1

fi

AGORA_MACRO="Hermes/Agora/AgoraMacro.h"
rm -rf AGORA_MACRO

SDK_VER=$2

VER_FIRST=${SDK_VER:0:1}

echo $VER_FIRST

if [ "$SDK_VER" == "carbon" ] ;then

    APP_BRANCH="release/3.0.0"
    echo "app branch $APP_BRANCH sdk ver $SDK_VER > 3.0.0"
    cp -r AgoraMacro.h $AGORA_MACRO

elif [ "$VER_FIRST" -ge "3" ] ;then

    APP_BRANCH="release/3.0.0"
    echo "app branch $APP_BRANCH sdk ver $SDK_VER > 3.0.0"
    cp -r AgoraMacro.h $AGORA_MACRO

else

    APP_BRANCH="release/2.9.0"
    echo "app branch $APP_BRANCH sdk ver $SDK_VER < 3.0.0"
    cp -r AgoraMacro_sdk290.h $AGORA_MACRO

fi

rm -rf $SDK_PATH >/dev/null

rm -rf $DST_PATH >/dev/null

mkdir -p $SDK_PATH

mkdir -p $DST_PATH

mkdir -p $RES_PATH

unzip $SDK_ZIP_PATH -d $PROJECT_PATH

if [ -d "${SDK_PATH}/libs/ALL_ARCHITECTURE/" ];then
  echo "exist ${SDK_PATH}/libs/ALL_ARCHITECTURE/ folder path"
  cp -R $SDK_PATH/libs/ALL_ARCHITECTURE/*.framework $SDK_PATH/libs/ALL_ARCHITECTURE/*.xcframework $SDK_PATH/libs/ALL_ARCHITECTURE/*.a $DST_PATH
else
  cp -R $SDK_PATH/libs/*.framework $SDK_PATH/libs/*.xcframework $SDK_PATH/libs/*.a $DST_PATH
fi

echo " RTC_SDK_VERSION= $SDK_VER  APP_BRANCH = $APP_BRANCH unzip_folder_path = $SDK_PATH"

./_APIParserTool RTC_SDK_VERSION=$SDK_VER APP_BRANCH=$APP_BRANCH unzip_folder_path=$SDK_PATH

if [ ! -f "$SRC_JSON" ];then
    echo "$SRC_JSON 文件不存在 APIParserTool"
    exit;
fi

cp $SRC_JSON $DST_JSON


rm -rf $SDK_PATH >/dev/null

rm -rvf frameworks >/dev/null

rm -rvf tmp >/dev/null

pod install
